package com.aplink.generic.handler;

import java.util.ArrayList;

import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;

import com.aplink.generic.GenericFragment;
import com.aplink.generic.adapter.ViewPagerAdapter;
import com.aplink.generic.constant.type.ActionType;
import com.aplink.generic.constant.type.DialogStatus;
import com.aplink.generic.controller.GenericApplication;
import com.aplink.generic.webservice.DataResult;
import com.aplink.generic.webservice.HttpResponseStatus;
import com.aplink.generic.webservice.ResponseStatus;

public class GenericHandler extends Handler {

    private final GenericFragment mGenericFragment;

    public GenericHandler(final GenericFragment genericFragment) {
        this.mGenericFragment = genericFragment;
    }

    private boolean checkLogin(final DataResult dataResult) {
        final HttpResponseStatus statusCode = dataResult.getServerResponse();
        if (statusCode.equals(HttpResponseStatus.SUCCESS)) {
            final ResponseStatus responseStatus = dataResult
                    .getResponseStatus();
            if (responseStatus.getStatus() == ResponseStatus.SUCCESS) {
                return true;
            } else if (responseStatus.getStatus() == ResponseStatus.LOGIN_FAILD) {
                return false;
            }
        } else {

        }
        return false;
    }

    @SuppressWarnings("unchecked")
    @Override
    public void handleMessage(final Message msg) {
        final ActionType actionType = ActionType.get(msg.what);
        if (actionType.equals(ActionType.NEXT_PAGE)) {
            this.mGenericFragment.nextPage();
        } else if (actionType.equals(ActionType.LOGIN)) {
            final ArrayList<DataResult> dataResults = (ArrayList<DataResult>) msg.obj;
            final DataResult dataResult = dataResults.get(0);
            if (checkLogin(dataResult)) {
                this.mGenericFragment.getDatabaseHandler().sendMessage(
                        ActionType.LOGIN, dataResult);
            } else {
                this.mGenericFragment.getDatabaseHandler().sendMessage(
                        ActionType.LOGIN, null);
            }
        } else if (actionType.equals(ActionType.INIT_DATA)) {
            handleWebserviceResponse(ActionType.INIT_DATA, msg);
        } else if (actionType.equals(ActionType.LOGOUT)) {
            GenericApplication.getInstance().logout(this.mGenericFragment);
        } else if (actionType.equals(ActionType.RESET_APPLICATION)) {
            GenericApplication.getInstance().resetApplication(
                    this.mGenericFragment);
        } else if (actionType.equals(ActionType.DOWNLOAD)) {
            handleWebserviceResponse(ActionType.DOWNLOAD, msg);
        } else if (actionType.equals(ActionType.DOWNLOAD_ALL)) {
            handleWebserviceResponse(ActionType.DOWNLOAD_ALL, msg);
        } else if (actionType.equals(ActionType.UPLOAD)) {
            handleWebserviceResponse(ActionType.UPLOAD, msg);
        } else if (actionType.equals(ActionType.INSERT)) {
            handleWebserviceResponse(ActionType.INSERT, msg);
        } else if (actionType.equals(ActionType.UPDATE)) {
            handleWebserviceResponse(ActionType.UPDATE, msg);
        } else if (actionType.equals(ActionType.DELETE)) {
            handleWebserviceResponse(ActionType.DELETE, msg);
        } else if (actionType.equals(ActionType.SAVE)) {
            handleWebserviceResponse(ActionType.SAVE, msg);
        } else if (actionType.equals(ActionType.REFRESH_PAGE)) {
            if (this.mGenericFragment.getView().getParent() instanceof ViewPager) {
                final ViewPager viewPager = (ViewPager) this.mGenericFragment
                        .getView().getParent();
                final ViewPagerAdapter pagerAdapter = (ViewPagerAdapter) viewPager
                        .getAdapter();
                for (int i = 0; i < pagerAdapter.getCount(); i++) {
                    final GenericFragment genericFragment = pagerAdapter
                            .getItem(i);
                    genericFragment.setAlowRefresh(true);
                    genericFragment.notifyDataSetChanged();
                }
            } else {
                this.mGenericFragment.setAlowRefresh(true);
                this.mGenericFragment.notifyDataSetChanged();
            }
        } else if (actionType.equals(ActionType.CLOSE)) {
            this.mGenericFragment.finishActivity();
        } else if (actionType.equals(ActionType.FORGOT_PASSWORD)) {
            handleWebserviceResponse(ActionType.FORGOT_PASSWORD, msg);
        }
    }

    @SuppressWarnings("unchecked")
    private void handleWebserviceResponse(final ActionType actionType,
            final Message message) {
        final ArrayList<DataResult> dataResults = (ArrayList<DataResult>) message.obj;
        if (dataResults.isEmpty()) {
            // TODO: NOT things to submit to server.
        } else {
            final DataResult dataResult = dataResults.get(0);
            final ResponseStatus responseStatus = dataResult
                    .getResponseStatus();
            final HttpResponseStatus httpResponseStatus = dataResult
                    .getServerResponse();
            if (httpResponseStatus.equals(HttpResponseStatus.SUCCESS)) {
                if (dataResult.getData().isEmpty() && (responseStatus != null)) {
                    if (responseStatus.getStatus() == ResponseStatus.SUCCESS) {
                        this.mGenericFragment.getDatabaseHandler().sendAction(
                                actionType);
                    } else if (responseStatus.getStatus() == ResponseStatus.INVAILD_TOKEN) {
                        this.mGenericFragment.getAlertDialog().show(actionType,
                                DialogStatus.INVALID_TOKEN);

                    } else if (responseStatus.getStatus() == ResponseStatus.FAILD) {
                        this.mGenericFragment.getAlertDialog().show(actionType,
                                DialogStatus.FAILD);
                    }
                } else {
                    this.mGenericFragment.getDatabaseHandler().sendMessage(
                            actionType, dataResults);
                }
            } else {
                this.mGenericFragment.getAlertDialog().show(actionType,
                        DialogStatus.HTTP_FAILED);
            }
        }
    }

    public void sendAction(final ActionType actionType) {
        sendEmptyMessage(actionType.getCode());
    }

    public void sendMessage(final ActionType actionType, final Object object) {
        final Message message = Message.obtain(this, actionType.getCode(),
                object);
        message.sendToTarget();
    }
}
